<!--
	此示例下载自 https://echarts.apache.org/examples/zh/editor.html?c=bar-race-country
-->
<!DOCTYPE html>
<html lang="zh-CN" style="height: 100%">

<head>
  <meta charset="utf-8">
</head>

<body style="height: 100%; margin: 0">
  <div id="container" style="height: 100%"></div>
  <script src="https://ajax.aspnetcdn.com/ajax/jquery/jquery-3.5.1.min.js"></script>
  <script type="text/javascript" src="https://fastly.jsdelivr.net/npm/jquery"></script>
  <script type="text/javascript" src="https://fastly.jsdelivr.net/npm/echarts@5.4.3/dist/echarts.min.js"></script>

  <script type="text/javascript">
    var dom = document.getElementById('container');
    var myChart = echarts.init(dom, null, {
      renderer: 'canvas',
      useDirtyRect: false
    });
    var app = {};
    var option;

    const updateFrequency = 2000;
    const dimension = 0;
    const countryColors = {
      Australia: '#00008b',
      Canada: '#f00',
      China: '#ffde00',
      Cuba: '#002a8f',
      Finland: '#003580',
      France: '#ed2939',
      Germany: '#000',
      Iceland: '#003897',
      India: '#f93',
      Japan: '#bc002d',
      'North Korea': '#024fa2',
      'South Korea': '#000',
      'New Zealand': '#00247d',
      Norway: '#ef2b2d',
      Poland: '#dc143c',
      Russia: '#d52b1e',
      Turkey: '#e30a17',
      'United Kingdom': '#00247d',
      'United States': '#b22234'
    };
    $.when(
      $.getJSON('./data.json'),
      $.getJSON('./life-expectancy-table.json')
    ).done(function (res0, res1) {
      // res0 是
      const flags = res0[0];
      const data = res1[0];
      const years = [];
      // 获取到所有的年份
      for (let i = 0; i < data.length; ++i) {
        // 假如years为空或者years的最后一项不等于当前data项的年份,那就说明是新的年份,就添加到years集合当中
        if (years.length === 0 || years[years.length - 1] !== data[i][4]) {
          years.push(data[i][4]);
        }
      }
      function getFlag (countryName) {
        if (!countryName) {
          return '';
        }
        return (
          flags.find(function (item) {
            return item.name === countryName;
          }) || {}
        ).emoji;
      }
      let startIndex = 0;
      console.log('startYear', years[startIndex]);
      let startYear = years[startIndex];
      option = {
        grid: {
          top: 10,
          bottom: 30,
          left: 150,
          right: 80
        },
        xAxis: {
          max: 'dataMax',
          axisLabel: {
            formatter: function (n) {
              return Math.round(n) + '';
            }
          }
        },
        dataset: {
          // 懂了 国家是有限的 比如只有十个国家 但是每一个国家都对应了上百条数据
          source: data.slice(1).filter(function (d) {
            return d[4] === startYear;
          })
        },
        yAxis: {
          type: 'category',
          // 倒序排序
          inverse: true,
          // max: 10,
          axisLabel: {
            // show: true,
            fontSize: 14,
            formatter: function (value) {
              // '{flag|' + `XXXX` + '}' 这种写法起到一个加粗的效果
              return value + '{flag|' + getFlag(value) + '}';
              // return value + getFlag(value) ;
            },
            rich: {
              flag: {
                fontSize: 25,
                padding: 5
              }
            }
          },
          // 下面两个属性是设置Y轴的更新速率,推荐使用这个数值,比较平滑
          animationDuration: 300,
          animationDurationUpdate: 300
        },
        series: [
          {
            realtimeSort: true,
            seriesLayoutBy: 'column',
            type: 'bar',
            itemStyle: {
              color: function (param) {
                return countryColors[param.value[3]] || '#5470c6';
              }
            },
            encode: {
              x: dimension,
              y: 3
            },
            label: {
              show: true,
              precision: 1,
              position: 'right',
              valueAnimation: true,
              fontFamily: 'monospace'
            }
          }
        ],
        // Disable init animation.
        animationDuration: 0,
        animationDurationUpdate: updateFrequency,
        animationEasing: 'linear',
        animationEasingUpdate: 'linear',
        graphic: {
          // 设置其它标志
          elements: [
            {
              type: 'text',
              right: 160,
              bottom: 60,
              style: {
                text: startYear,
                font: 'bolder 60px monospace',
                fill: 'rgba(100, 100, 100, 0.25)'
              },
              z: 100
            }
          ]
        }
      };
      myChart.setOption(option);
      for (let i = startIndex; i < years.length - 1; ++i) {
        (function (i) {
          // 每隔一段时间更新一次
          setTimeout(function () {
            updateYear(years[i + 1]);
          }, (i - startIndex) * updateFrequency);
        })(i);
      }
      function updateYear (year) {
        let source = data.slice(1).filter(function (d) {
          return d[4] === year;
        });
        option.series[0].data = source;
        option.graphic.elements[0].style.text = year;
        myChart.setOption(option);
      }
    });

    if (option && typeof option === 'object') {
      myChart.setOption(option);
    }

    window.addEventListener('resize', myChart.resize);
  </script>
</body>

</html>